package org.truenewx.tnxjee.webmvc.response;

import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.truenewx.tnxjee.service.exception.MultiException;
import org.truenewx.tnxjee.service.exception.ResolvableException;
import org.truenewx.tnxjee.service.exception.model.CodedError;
import org.truenewx.tnxjee.service.exception.model.ExceptionError;
import org.truenewx.tnxjee.webmvc.response.reminder.model.ReminderMessage;

/**
 * RPC响应
 */
public class RpcResponse {

    private Object result;
    private List<ExceptionError> errors;
    private List<ReminderMessage> reminders;

    public static RpcResponse ok(Object data) {
        RpcResponse result = new RpcResponse();
        result.setResult(data);
        return result;
    }

    public static RpcResponse error(List<ExceptionError> errors) {
        RpcResponse result = new RpcResponse();
        result.setErrors(errors);
        return result;
    }

    public static RpcResponse error(ExceptionError... errors) {
        return error(List.of(errors));
    }

    public Object getResult() {
        return this.result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public List<ExceptionError> getErrors() {
        return this.errors;
    }

    public void setErrors(List<ExceptionError> errors) {
        this.errors = errors;
    }

    public List<ReminderMessage> getReminders() {
        return this.reminders;
    }

    public void setReminders(List<ReminderMessage> reminders) {
        this.reminders = reminders;
    }

    public boolean isSuccessful() {
        return this.errors == null || this.errors.isEmpty();
    }

    public ResolvableException toException() {
        if (CollectionUtils.isNotEmpty(this.errors)) {
            if (this.errors.size() == 1) {
                ExceptionError error = this.errors.get(0);
                return error.toException();
            } else {
                MultiException me = new MultiException();
                for (ExceptionError error : this.errors) {
                    me.add(error.toException());
                }
                return me;
            }
        }
        return null;
    }

}
